package cn.chenwx.controller;

import cn.chenwx.entity.ResultMap;
import cn.chenwx.mapper.UserMapper;
import cn.chenwx.utils.JWTUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;



@RestController
public class AdminController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JWTUtil jwtUtil;

    @PostMapping("/login")
    public ResultMap login(@RequestParam("username") String username,
                           @RequestParam("password") String password, HttpServletResponse response) {
        String realPassword = userMapper.getPassword(username);
        if (realPassword == null) {
            return ResultMap.errorException("用户名错误！");
        } else if (!realPassword.equals(password)) {
            return ResultMap.errorException("密码错误！");
        } else {
            String jwt = jwtUtil.createToken(username);
            response.setHeader("Authorization",jwt); // 相当于项目中的AccessToken
            response.setHeader("Access-control-Expose-Headers","Authorization");
            HashMap<String, Object> map = new HashMap<>();
            map.put("accessToken",JWTUtil.createToken(username));
            map.put("refreshToken ",JWTUtil.createNewToken(username));
            return ResultMap.ok(map);
        }
    }

    @RequiresAuthentication
    @RequiresRoles("admin")
    @RequestMapping(path = "/authorized")
    public ResultMap unauthorized(@RequestParam("message") String message, HttpServletRequest request)  {

        return ResultMap.build(401,message,request.getHeader("Token"));
    }

}
